<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRole">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一级权限 -->
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['b-bottom', 'v-center', i1 == '0' ? 'b-top' : '']"
            >
              <el-col :span="5">
                <el-tag closable @close="removeRoleById(scope.row, item1.id)">{{
                  item1.authName
                }}</el-tag>
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 == '0' ? '' : 'b-top', 'v-center']"
                >
                  <el-col :span="5">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRoleById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                  </el-col>
                  <el-col :span="19">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRoleById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRoleById(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeRole(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightsDialog(scope.row)"
              >权限分配</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%">
      <el-form
        ref="addRoleFormRef"
        :rules="addRoleFormRule"
        :model="addRoleForm"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色信息"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <el-form
        ref="editRoleFormRef"
        :rules="editRoleFormRule"
        :model="editRoleForm"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
      @close="setRightsDialogClosed"
    >
      <el-tree
        :data="rightList"
        :props="treeProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defKeys"
        ref="setRightsTreeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      addDialogVisible: false,
      /* 添加角色表单 */
      addRoleForm: {
        roleName: '',
        roleDesc: '',
      },
      /* 添加角色表单验证规则 */
      addRoleFormRule: {
        roleName: [
          {
            required: true,
            message: '请输入要添加的角色名称',
            trigger: 'blur',
          },
          { min: 3, max: 8, message: '角色名称长度需要在3-8', trigger: 'blur' },
        ],
        roleDesc: [
          {
            required: true,
            message: '请输入要添加的角色的描述',
            trigger: 'blur',
          },
          {
            min: 8,
            max: 20,
            message: '角色名称长度需要在8-20',
            trigger: 'blur',
          },
        ],
      },
      /* 编辑角色信息对话框显示 */
      editDialogVisible: false,
      /* 编辑角色信息表单 */
      editRoleForm: {},
      /* 编辑角色信息表单验证规则 */
      editRoleFormRule: {
        roleName: [
          {
            required: true,
            message: '请输入要添加的角色名称',
            trigger: 'blur',
          },
          { min: 3, max: 8, message: '角色名称长度需要在3-8', trigger: 'blur' },
        ],
        roleDesc: [
          {
            required: true,
            message: '请输入要添加的角色的描述',
            trigger: 'blur',
          },
          {
            min: 8,
            max: 20,
            message: '角色名称长度需要在8-20',
            trigger: 'blur',
          },
        ],
      },
      /* 控制分配权限对话框的显示与隐藏 */
      setRightsDialogVisible: false,
      rightList: [],
      treeProps: {
        children: 'children',
        label: 'authName',
      },
      //默认勾选的权限的id
      defKeys: [],
      /* 保存当前分配权限的角色id */
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.rolesList = res.data
    },
    /* 点击添加角色按钮 */
    addRole() {
      this.addDialogVisible = true
    },
    /* 点击添加角色表单中确定按钮 */
    addRoleInfo() {
      this.$refs.addRoleFormRef.validate(async (valid) => {
        if (!valid) return console.log('角色信息填写格式错误！')
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败！')
        }
        this.$message.success('添加角色成功！')
        this.addDialogVisible = false
        this.getRolesList()
      })
    },
    /* 编辑角色信息 */
    async editRoleById(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败！')
      }
      this.editRoleForm = res.data
      this.editDialogVisible = true
    },
    /* 编辑角色信息确认按钮 */
    editRoleInfo() {
      this.$refs.editRoleFormRef.validate(async (valid) => {
        if (!valid) return console.log('角色信息格式填写错误！')
        const { data: res } = await this.$http.put(
          'roles/' + this.editRoleForm.roleId,
          {
            roleName: this.editRoleForm.roleName,
            roleDesc: this.editRoleForm.roleDesc,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('角色信息修改失败！')
        }
        this.$message.success('角色信息修改成功！')
        this.editDialogVisible = false
        this.getRolesList()
      })
    },
    /* 删除角色 */
    removeRole(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete('roles/' + id)
          if (res.meta.status !== 200) {
            return this.$message.error('删除角色失败！')
          }
          this.$message.success('删除角色成功！')
          this.getRolesList()
        })
        .catch(() => {
          this.$message.info('取消删除该角色！')
        })
    },
    /* 根据id删除权限 */
    removeRoleById(role, rightId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          )
          if (res.meta.status !== 200) {
            return this.$message.error('权限删除失败！')
          }
          this.$message.success('权限删除成功！')
          //this.getRolesList()  会造成页面的完整刷新
          role.children = res.data
        })
        .catch(() => {
          this.$message.info('取消删除该权限！')
        })
    },
    /* 显示权限分配对话框 */
    async showSetRightsDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限失败！')
      }
      this.rightList = res.data
      this.setRightsDialogVisible = true
      this.searchRightId(role, this.defKeys)
    },
    /* 递归查询三级权限 */
    searchRightId(role, arr) {
      if (!role.children) {
        return arr.push(role.id)
      }
      role.children.forEach((item) => {
        this.searchRightId(item, arr)
      })
    },
    /* 监听分配权限对话框的关闭 */
    setRightsDialogClosed() {
      this.defKeys = []
    },
    /* 分配权限对话框的提交确定 */
    async allotRights() {
      const rTree = this.$refs.setRightsTreeRef
      const rights = [...rTree.getCheckedKeys(),...rTree.getHalfCheckedKeys()]
      const rightStr = rights.join(',')
      const { data:res } = await this.$http.post(`roles/${this.roleId}/rights`, {rids:rightStr})
      if(res.meta.status !== 200){
        return this.$message.error('权限分配失败！')
      }
      this.$message.success('权限分配成功！')
      this.setRightsDialogVisible = false
      this.getRolesList()
    }
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px 5px;
}
.b-top {
  border-top: 1px solid #eee;
}
.b-bottom {
  border-bottom: 1px solid #eee;
}

/* 垂直居中 */
.v-center {
  display: flex;
  align-items: center;
}
</style>